package com.yl.users.services.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.common.ErrorCode
import com.yl.common.ErrorCode.*
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.entity.CompanyDept
import com.yl.users.entity.CompanyLinkDeptUser
import com.yl.users.entity.CompanyLinkSubCompanyDeptUser
import com.yl.users.entity.CompanyUser
import com.yl.users.services.ICompanyDeptService
import com.yl.users.mapper.CompanyDeptMapper
import com.yl.users.mapper.CompanyLinkDeptUserMapper
import com.yl.users.mapper.CompanyLinkSubCompanyDeptUserMapper
import com.yl.users.pojo.vo.CompanyDeptSelectVo
import com.yl.users.pojo.vo.CompanyUserSelectVo
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
open class CompanyDeptServiceImpl(

	private val companyDeptMapper: CompanyDeptMapper,

	private val companyLinkDeptUserMapper: CompanyLinkDeptUserMapper,

	private val companyLinkSubCompanyDeptUserMapper: CompanyLinkSubCompanyDeptUserMapper,


) : ICompanyDeptService {

	@Autowired
	private lateinit var iCompanyUserService: ICompanyUserService

	companion object {
		private val log = LoggerFactory.getLogger(ICompanyDeptService::class.java)
	}

	override fun addSubDept(dept: CompanyDept): ResponseBody {
		val companyDept = companyDeptMapper.selectById(dept.superDeptId) ?: return returnError(PARAM_EMPTY, "请选择上级")
		dept.subCompanyId = companyDept.subCompanyId
		companyDeptMapper.insert(dept)
		return bindSuperDept(dept.id, dept.superDeptId)
	}

	override fun getDept(id: Long): CompanyDept? {
		return companyDeptMapper.selectById(id)
	}

	override fun bindSuperDept(deptId: Long, superDeptId: Long): ResponseBody {
		val companyDept = companyDeptMapper.selectById(deptId)
		if (companyDept.superDeptId == 0L) {
			return returnError(DATA_SAVE_FAILED, "总部不能添加上级部门")
		}
		val superDept = companyDeptMapper.selectById(superDeptId) ?: return returnError(DATA_SAVE_FAILED, "上级部门未找到")
		if (companyDept.companyId != superDept.companyId) {
			return returnError(DATA_SAVE_FAILED, "上级部门选择错误")
		}
		if (deptHaveSubId(companyDept.id, superDeptId, companyDept.companyId)) {
			return returnError(DATA_SAVE_FAILED, "上级部门选择错误")
		}
		companyDept.superDeptId = superDeptId
		companyDept.subCompanyId = superDept.subCompanyId
		companyDeptMapper.updateById(companyDept)
		return returnSuccess()
	}

	override fun delDept(id: Long): ResponseBody {
		val dept = companyDeptMapper.selectById(id) ?: return returnError(DATA_IS_NOT_FIND)
		if (dept.superDeptId == 0L) {
			return returnError(DATA_DELETE_FAILED, "总部不能删除")
		}
		if(dept.subCompany == 1){
			return returnError(DATA_DELETE_FAILED, "不能删除分部")
		}
		if (companyDeptMapper.selectCount(Wrappers.query<CompanyDept?>().eq("super_dept_id", id).eq("enabled", 1)) != 0)
			return returnError(DATA_DELETE_FAILED, "存在子级部门")
		dept.enabled = 0
		companyDeptMapper.updateById(dept)
		return returnSuccess()
	}

	override fun deptHaveSubId(deptId: Long, subId: Long, companyId: Long): Boolean {
		return companyDeptMapper.selectHaveSubId(deptId, subId, companyId) != 0
	}

	override fun updateDeptInfo(companyDept: CompanyDept): ResponseBody {
		val dept = companyDeptMapper.selectById(companyDept.id) ?: return returnError(DATA_IS_NOT_FIND)
		dept.name = companyDept.name
		dept.phone = companyDept.phone
		dept.address = companyDept.address
		dept.addressPoint = companyDept.addressPoint
		companyDeptMapper.updateById(dept)
		return returnSuccess()
	}

	override fun updateDept(companyDept: CompanyDept): ResponseBody {
		val dept = companyDeptMapper.selectById(companyDept.id) ?: return returnError(DATA_IS_NOT_FIND)

		if (dept.superDeptId == 0L) {
			companyDept.superDeptId != 0L
			return returnError(DATA_SAVE_FAILED, "总部不能添加上级部门")
		}
		if (dept.subCompany == 1) {
			//分部和总部不能更换上级部门
			if (dept.superDeptId != companyDept.superDeptId) {
				return returnError(DATA_SAVE_FAILED, "不能更换上级部门")
			}
		} else {
			//不支持跨分公司转移部门
			val superDept = companyDeptMapper.selectById(companyDept.superDeptId)
			if (superDept.subCompanyId != dept.subCompanyId) {
				return returnError(DATA_SAVE_FAILED, "不能更换上级部门")
			}
			//
			if (deptHaveSubId(companyDept.id, companyDept.superDeptId, companyDept.companyId)) {
				return returnError(DATA_SAVE_FAILED, "上级部门选择错误")
			}
		}
		companyDeptMapper.updateById(companyDept)
		return returnSuccess()
	}

	override fun getUserList(deptId: Long, vo: CompanyUserSelectVo): MutableList<CompanyUser> {
		return companyLinkDeptUserMapper.selectDeptUserList(vo, deptId)
	}

	override fun getUserPage(page: Page<CompanyUser>, vo: CompanyUserSelectVo, deptId: Long): Page<CompanyUser> {
		return companyLinkDeptUserMapper.selectDeptUserPage(page, vo, deptId)
	}

	override fun bindUserToDept(deptId: Long, userId: Long): ResponseBody {
		log.info("部门管理==>部门绑定用户，并绑定分院 userId:{},deptId:{}", userId, deptId)
		val companyDept = companyDeptMapper.selectById(deptId) ?: return returnError(DATA_IS_NOT_FIND, "未找到部门")

		if (companyLinkDeptUserMapper.selectCount(
				QueryWrapper<CompanyLinkDeptUser?>().eq("user_id", userId).eq("dept_id", deptId)
			) == 0
		) {
			companyLinkDeptUserMapper.insert(CompanyLinkDeptUser(userId = userId, deptId = deptId))
		}
		return bindUserToSubCompany(userId, companyDept.subCompanyId!!)
	}

	override fun unBindUserDept(deptId: Long, userId: Long): ResponseBody {
		val dept = getDept(deptId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND,"找不到该部门")

		companyLinkDeptUserMapper.delete(
			QueryWrapper<CompanyLinkDeptUser?>().eq("user_id", userId).eq("dept_id", deptId)
		)
		if(!iCompanyUserService.userIsInSubCompanyDept(dept.subCompanyId,userId)){
			return unBindUserToSubCompany(userId,dept.subCompanyId)
		}
		return returnSuccess()
	}

	override fun bindUserToSubCompany(userId: Long, subCompanyId: Long): ResponseBody {
		if (companyLinkSubCompanyDeptUserMapper.selectCount(
				QueryWrapper<CompanyLinkSubCompanyDeptUser?>()
					.eq("user_id", userId)
					.eq("company_dept_id", subCompanyId)
			) == 0
		) {
			companyLinkSubCompanyDeptUserMapper.insert(CompanyLinkSubCompanyDeptUser(userId, subCompanyId))
		}
		return returnSuccess()
	}

	override fun unBindUserToSubCompany(userId: Long, subCompanyId: Long): ResponseBody {

		val unBindRoleBySubCompanyId = iCompanyUserService.unBindRoleBySubCompanyId(userId, subCompanyId)
		if(unBindRoleBySubCompanyId.bodyIsError()){
			return unBindRoleBySubCompanyId
		}
		companyLinkSubCompanyDeptUserMapper.delete(
			Wrappers.query<CompanyLinkSubCompanyDeptUser?>()
				.eq("user_id", userId)
				.eq("company_dept_id",subCompanyId)
		)
		return returnSuccess()
	}

	override fun getSubCompanyUserPage(
		page: Page<CompanyUser>,
		vo: CompanyUserSelectVo,
		subCompanyId: Long
	): Page<CompanyUser> {
		return companyLinkDeptUserMapper.getSubCompanyUserPage(page, vo, subCompanyId)
	}

	override fun getSubCompanyUserList(
		vo: CompanyUserSelectVo,
		subCompanyId: Long
	): MutableList<CompanyUser> {
		return companyLinkDeptUserMapper.getSubCompanyUserList(vo, subCompanyId)
	}


	override fun getSubCompanyList(deptId: Long): MutableList<CompanyDept> {
		return companyDeptMapper.getSubCompanyList(deptId)
	}


	override fun getSubCompanyDeptPage(page: Page<CompanyDept>, companyDept: CompanyDeptSelectVo): Page<CompanyDept> {
		if (companyDept.subCompanyId == null) {
			companyDept.subCompanyId = getContext().subCompanyId

		}
		companyDept.subCompany = 0

		return companyDeptMapper.selectDeptPage(page, companyDept)
	}

	override fun getSubCompanyDeptList(vo: CompanyDeptSelectVo): MutableList<CompanyDept> {
		if (vo.subCompanyId == null) {
			vo.subCompanyId = getContext().subCompanyId

		}
		vo.subCompany = 0

		return companyDeptMapper.selectDeptList( vo)
	}

	override fun getUserByDeptId(page: Page<CompanyUser>, vo: CompanyUserSelectVo, deptId: Long): Page<CompanyUser> {
		if(vo.onlySelfDept == true){
			if(vo.deptId == null){
				vo.deptId = getContext().subCompanyId
			}
		}else{
			vo.deptId = null
		}

		return companyLinkDeptUserMapper.selectUserByDeptId(page,vo,deptId, getContext().companyId)
	}

	override fun getLastLoginHavePremUsers(subCompanyId: Long, permCode: String): List<CompanyUser> {
		val userList = getSubCompanyUserList( CompanyUserSelectVo(lastLoginSubCompanyId = subCompanyId),subCompanyId)
		userList.removeIf { !iCompanyUserService.havePermCode(getContext().companyId, it.id, permCode, subCompanyId) }
		return userList
	}
}
